package com.demo.services.impl;

import com.demo.common.AppResult;
import com.demo.common.ResultCode;
import com.demo.dao.ArticleReplyMapper;
import com.demo.exception.ApplicationException;
import com.demo.model.ArticleReply;
import com.demo.services.IArticleReplyService;
import com.demo.services.IArticleService;
import com.demo.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author quan
 * @Description 回复帖
 * @Date 2023/8/15 9:07
 */

@Service
@Slf4j
public class ArticleReplyServiceImpl implements IArticleReplyService {

    @Resource
    private ArticleReplyMapper articleReplyMapper;

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        //1-参数校验
        if(articleId == null || articleId<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2-调用mapper
        List<ArticleReply> articleReplies = articleReplyMapper.selectByArticleId(articleId);
        //3-返回结果
        return articleReplies;
    }

    @Override
    public void create(ArticleReply articleReply) {
        //1-必传参数校验:回复表、提交人id，要回复的帖子Id、回复内容是否为空
        if(articleReply == null || articleReply.getArticleId() == null
        || articleReply.getPostUserId() == null || StringUtils.isEmpty(articleReply.getContent())){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2-给回复表的其他属性设置默认值
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setLikeCount(0);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);
        Date date = new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);
        //3-调用mapper的insert
        int row = articleReplyMapper.insertSelective(articleReply);
        //4-校验row
        if(row!=1){
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //5-不报错表示执行成功。
    }
}
